package vworld.dao.message;

import generated.domain.message.Message;

import org.hibernate.HibernateException;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.Transaction;

import vworld.dao.HibernateUtil;

public class MessageDAO {

	public void createMessage(Message _pMessage) {
		Transaction tx = null;
		Session session = HibernateUtil.currentSession();
		try {
			tx = session.beginTransaction();
			session.save(_pMessage);
			tx.commit();
		} catch (HibernateException e) {
			e.printStackTrace();
			if (tx != null && tx.isActive())
				tx.rollback();
		} finally {
			HibernateUtil.closeSession();
		}
	}

	public void deleteMessage(Message _pMessage) {
		Transaction tx = null;
		Session session = HibernateUtil.currentSession();
		try {
			tx = session.beginTransaction();
			session.delete(_pMessage);
			tx.commit();
		} catch (HibernateException e) {
			e.printStackTrace();
			if (tx != null && tx.isActive())
				tx.rollback();
		} finally {
			HibernateUtil.closeSession();
		}
	}

	public void saveOrUpdateMessage(Message _pMessage) {
		Transaction tx = null;
		Session session = HibernateUtil.currentSession();
		try {
			tx = session.beginTransaction();
			// session.saveOrUpdate(pRoom.getInsideAvatars());
			session.saveOrUpdate(_pMessage);
			tx.commit();
		} catch (HibernateException e) {
			e.printStackTrace();
			if (tx != null && tx.isActive())
				tx.rollback();
		} finally {
			HibernateUtil.closeSession();
		}
	}

	public Message[] getMessages(String pReceiverName) {
		try {
			Session session = HibernateUtil.currentSession();
			Query query = session
					.createQuery("from Message m where m.receiver = :receiver");
			query.setString("receiver", pReceiverName);

			return (Message[]) query.list().toArray(
					new Message[query.list().size()]);
		} finally {
			HibernateUtil.closeSession();
		}
	}

}
